package com.aptemo.webetek.server.handlers;

import java.util.List;

import javax.jdo.PersistenceManager;

import com.aptemo.webetek.client.commands.Action;
import com.aptemo.webetek.client.commands.impl.GetLoginInfoAction;
import com.aptemo.webetek.client.exceptions.BackendException;
import com.aptemo.webetek.server.data.PMF;
import com.aptemo.webetek.server.data.WebetekUser;
import com.aptemo.webetek.server.datastore.DataStoreAPI;
import com.aptemo.webetek.shared.LoginBean;
import com.google.appengine.api.users.User;

public class LoginInfoHandler
		extends ActionHandler<GetLoginInfoAction, LoginBean>
{

	public LoginInfoHandler(DataStoreAPI service)
	{
		super(service);
	}

	@Override
	public Class<? extends Action<?>> getActionType()
	{
		return GetLoginInfoAction.class;
	}

	@Override
	public LoginBean invoke(GetLoginInfoAction action) throws BackendException
	{
		String path = action.getPath();

		PersistenceManager pm = PMF.get().getPersistenceManager();

		try
		{
			LoginBean login = null;
			User currentUser = userService.getCurrentUser();
			if (null == currentUser)
			{
				login = new LoginBean("");
			}
			else
			{
				String email = currentUser.getEmail();
				login = new LoginBean(email);
				if ((userService.isUserAdmin()))
				{
					login.setAdmin(true);
					// UserGroupBean usergroup = createUserGroup("AdminGroup",
					// "Predefined Admin group", false);
					List<WebetekUser> wuser = utils.getUser(pm, email);
					if (wuser.size() == 0)
					{
						// create user admin if none
						// createAdminUser(email);
					}
				}
				else
				{
				}

				// TODO set favourites
				// get login info...
				// login.setFavourites();

			}

			login.setLoggedIn(userService.isUserLoggedIn());
			login.setLoginUrl(userService.createLoginURL(path));
			login.setLogoutUrl(userService.createLogoutURL(path));

			return login;
		}
		finally
		{
			pm.close();
		}
	}
}
